package app.auto.designer.intfs.intf;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

import app.auto.designer.R;
import app.auto.designer.ActivityBase;
import app.auto.designer.tool.PathUtil;
import app.auto.runner.base.DialogUtil;
import app.auto.runner.base.MapAdapter;
import app.auto.runner.base.MapViewConf;
import app.auto.runner.base.action.ViewInflater;
import app.auto.runner.base.intf.JsonUtil;
import app.auto.runner.base.intf.json.JsonToMapUtils;
import app.auto.runner.base.utility.MapUtil;
import app.auto.runner.func.Http;
import app.auto.runner.base.stringtask.Requireinput;

public class SetParamActivity extends ActivityBase {
    private static final int REQUEST_CODE_CHANGE_PARAM = 2;
    Map<String, String> jsonparams = new TreeMap<String, String>();
    public int REQUEST_CODE_DEL = 1;
    private int position;
    private AdapterView<?> parent;

    //    Properties p = new Properties();
//    try {
//        p.load(new InputStreamReader(new FileInputStream(new File(PathUtil.intfpath)), "utf-8"));
//    } catch (IOException e) {
//        e.printStackTrace();
//        showToast(e.getMessage());
//
//    }
//
//    try {
//        p.store(new FileOutputStream(new File(PathUtil.intfpath)), "add " + key);
//    } catch (IOException e) {
//        e.printStackTrace();
//        showToast(e.getMessage());
//    }
    boolean canItemCLick = true;
    private String intf;
    private String url;
    private String description;
    private String params;
    String intfid;

    private Map instmap = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.auto_http);

        String data_id = getIntent().getStringExtra("data_id");
        if(data_id==null){
            data_id = new Random(6).nextLong()+"";
        }
        final String dataid = data_id;
        final String data_editable = getIntent().getStringExtra("data_editable");
        getContentView().findViewById(R.id.test).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getIntf();
                String params = null;
                try {
                    params = new JSONObject(intf).getString("type");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                String json_params = MapUtil.build().get(params).sure("name-defaultvalue").transfer().toJson();

                new Http().run(v, intf, json_params);

            }
        });
        getContentView().findViewById(R.id.save_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(getTextView(R.id.intfid).getText().toString())) {
                    new Requireinput().with((Activity) v.getContext()).exeId_Exp("intfid:接口id不能为空");
                    return;
                }
                getIntf();
                Intent intent = new Intent();
                if (TextUtils.isEmpty(data_editable) || data_editable.equals("false")) {
                    intent.putExtra("inst", JsonToMapUtils.mapToJson(instmap));
                }
                intent.putExtra("key", intfid).putExtra("data_id", dataid);
                setResult(0, intent);
                new PathUtil(PathUtil.intfpath).addKeyV(dataid, intf);
                showToast("已保存");

            }
        });
        JSONObject jsonobejct = new JSONObject();
        String login = "{\"description\":\"登录\"}";
        ((ListView) findViewById(R.id.param)).setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (canItemCLick) {
                    startActivityForResult(new Intent(view.getContext(), SetParamActivityDialog.class).putExtra("data_inst", instmap == null || instmap.size() == 0 ? null : JsonToMapUtils.mapToJson(instmap)).putExtra("data", JsonToMapUtils.mapToJson((Map) parent.getItemAtPosition(position))), 0);
                }
            }
        });


        setTitle("编辑模板");

        findViewById(R.id.addope).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(v.getContext(), SetParamActivityDialog.class).putExtra("data_editable", "true"), 0);
            }
        });

        ((ListView) findViewById(R.id.param)).setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                SetParamActivity.this.position = position;
                SetParamActivity.this.parent = parent;
                startActivityForResult(new Intent(parent.getContext(), DelActivity.class), REQUEST_CODE_DEL);
                canItemCLick = false;
                return false;
            }

        });
        loadData();
        getEditText(R.id.intfid).setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    getIntf();
                }
            }
        });
        getEditText(R.id.url).setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    getIntf();
                }
            }
        });
        getEditText(R.id.description).setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    getIntf();
                }
            }
        });
        getRadioButton(R.id.POST).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                getIntf();
            }
        });
        getRadioButton(R.id.GET).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                getIntf();
            }
        });
        String inst = getIntent().getStringExtra("data_inst");

        String data = new PathUtil(PathUtil.intfpath).getKeyedV(dataid);
        if (data != null&&!data.equals("")) {
            Map map = (Map) JsonUtil.extractJsonRightValue(data);
            List listmap;
            if (map.get("params") instanceof String) {
                if (map.get("params").equals("")) {
                    listmap = new ArrayList();
                } else {
                    listmap = (List) map.get("params");
                }
            } else {
                listmap = (List) map.get("params");
            }

            if (inst != null) {
                instmap = (Map) app.auto.runner.base.JsonUtil.extractJsonRightValue(inst);
                setTitle("编辑实例");
            }
            for (Object o : listmap) {
                String name = ((Map) o).get("name").toString();
                if (inst != null) {
                    ((Map) o).put("defaultvalue", instmap.get(name));
                }
                jsonparams.put(name, JsonToMapUtils.entityToJson(o));
            }
            MapViewConf mvc = MapViewConf.with(getBaseContext()).pair("description->description").pair("name->left").pair("type->center", "param:参数拼接;intfpath:路径拼接").pair("defaultvalue->right").source(R.layout.auto_param_item);
            MapViewConf.with(this).pair("id->intfid").pair("url->url").pair("description->description").pair("params->param", mvc).source(map, this).toView();
            String type = (String) map.get("type");
            if (type.toLowerCase().equals("post")) {
                ((RadioButton) findViewById(R.id.POST)).setChecked(true);
            } else {
                ((RadioButton) findViewById(R.id.GET)).setChecked(true);
            }
        }
        getTextView(R.id.domain).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final PathUtil su = new PathUtil(PathUtil.sys_var_path);
                if (su.hasKey("domain")) {
                    String domain = su.getKeyedV("domain");
                    String txt = getTextString(R.id.url);
                    if (txt.contains(domain)) {

                    } else {
                        getTextView(R.id.url).setText(domain + txt);

                    }
                } else {
                    DialogUtil.DialogInfo d = new DialogUtil.DialogInfo(v.getContext());
                    d.aty = v.getContext();
                    d.title = "默认域名";
                    final View view = d.view = new ViewInflater(v.getContext()).inflate(R.layout.auto_editetext, null);

                    d.neutralButtonText = "OK";
                    d.neutralButtonClickListener = new DialogUtil.DialogClicker() {
                        @Override
                        public void onClick(DialogInterface dialog, int arg1) {
                            su.addKeyV("domain", ((TextView) view.findViewById(R.id.domain)).getText().toString());
                            super.onClick(dialog, arg1);
                        }
                    };
                    if (!TextUtils.isEmpty(su.getKeyedV("domain"))) {
                        ((TextView) view.findViewById(R.id.domain)).setText(su.getKeyedV("domain"));
                    }
                    DialogUtil.showNeutralDialog(d, true);
                    return;
                }

            }
        });
        getTextView(R.id.domain).setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                final PathUtil su = new PathUtil(PathUtil.sys_var_path);
                if (su.hasKey("domain")) {
                    su.rmKey("domain");
                    view.performClick();
                }
                return false;
            }
        });
        if (TextUtils.isEmpty(getTextString(R.id.intfid))) {
            getTextView(R.id.intfid).setText(new Random().nextLong() + "");
        }
        getView(R.id.intfid).setVisibility(View.GONE);

        if (data_editable == null || data_editable.equals("false")) {
            View[] views = new View[]{getView(R.id.url), getView(R.id.domain), getView(R.id.description), getView(R.id.POST), getView(R.id.GET), getView(R.id.addope)};
            for (View v : views) {
                v.setEnabled(false);
            }
            ((ListView) getView(R.id.param)).setLongClickable(false);
            ((ListView) getView(R.id.param)).setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    if (canItemCLick) {
                        startActivityForResult(new Intent(view.getContext(), SetParamActivityDialog.class).putExtra("data_inst", instmap == null || instmap.size() == 0 ? null : JsonToMapUtils.mapToJson(instmap)).putExtra("data", JsonToMapUtils.mapToJson((Map) parent.getItemAtPosition(position))).putExtra("data_editable", "true"), 0);
                    }
                }
            });
        }
    }


    @NonNull
    private TextWatcher submitSave() {
        return new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                getIntf();
            }
        };
    }

    private String getIntf() {
        JSONObject job = new JSONObject();
        try {
            url = getTextString(R.id.url);
            url = url == null ? "" : url;
            job.put("url", "" + url);

            intfid = getTextString(R.id.intfid);
            intfid = intfid == null ? "" : intfid;
            job.put("id", "" + intfid);

            description = getTextString(R.id.description);
            description = description == null ? "" : description;
            job.put("description", "" + description);
            String type = "get";
            if (((RadioButton) getView(R.id.POST)).isChecked()) {
                type = "post";
            }
            job.put("type", "" + type);

            JSONArray array = new JSONArray();
            for (Object val : jsonparams.values()) {
                array.put(val.toString());
            }

            String prms = array.toString();
            prms = prms == null || prms.equals("[]") ? "" : prms;
            job.put("params", "" + prms);

        } catch (JSONException e) {
            e.printStackTrace();
        }


        return intf = job.toString();
    }

    //key
    private void del(AdapterView<?> parent, int position) {
        String name = (String) ((Map) ((MapAdapter) parent.getAdapter()).getItem(position)).get("name");
        rmdAPPCONFKey(name);

        ((MapAdapter) parent.getAdapter()).notifyDataSetChanged();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE_DEL) {
            canItemCLick = true;
            if (data != null) {
                String del = data.getStringExtra("del");
                if (del != null && del.equals("true")) {
                    del();
                }
            }
        } else {
            if (data != null) {
                addTo_APPCONF_(data);
            }

        }
        getIntf();
    }

    public void del() {
        del(this.parent, this.position);
    }

    public void loadData() {
        addTo_APPCONF_(new Intent());
    }


    private List delfrom_APPCONF(Set keys) {
        String key = null;
        for (Object o : keys) {
            key = o.toString();
            if (key != null) {
                jsonparams.remove(key);
            }
        }
        List list = fillToInterfaceView();
        return list;
    }

    @NonNull
    private List fillToInterfaceView() {
        List list = loadAPPCONF_values();
        Collections.sort(list, new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                if (((Map) o1).get("idx") == null) {
                    ((Map) o1).put("idx", "0");
                }
                if (((Map) o2).get("idx") == null) {
                    ((Map) o2).put("idx", "0");
                }
                return Integer.parseInt(((Map) o1).get("idx").toString()) - Integer.parseInt(((Map) o2).get("idx").toString());
            }
        });
        MapViewConf.with(getBaseContext()).conf(MapViewConf.with(getBaseContext()).pair("description->description").pair("name->left").pair("type->center", "param:参数拼接;intfpath:路径拼接").pair("defaultvalue->right").source(R.layout.auto_param_item)).source(list, findViewById(R.id.param)).toView();
        return list;
    }


    private List addTo_APPCONF_(Intent data) {

        String resultjson = data.getStringExtra("data");
        String key = data.getStringExtra("key");


        if (key != null) {
            if (!jsonparams.containsKey(key)) {
                try {
                    resultjson = new JSONObject(resultjson).put("idx", jsonparams.keySet().size() + "").toString();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
        if (key != null) {
            jsonparams.put(key, resultjson);
        }
        List list = fillToInterfaceView();
        return list;
    }

    private List loadAPPCONF_values() {
        List rt = new ArrayList();
        List list = new ArrayList(jsonparams.values());
        for (Object s : list) {
            rt.add(JsonUtil.extractJsonRightValue(s.toString()));
        }
        return rt;
    }

    private void rmdAPPCONFKey(String key) {
        delfrom_APPCONF(new TreeSet<String>(Arrays.asList(new String[]{key})));
        return;
    }


    public static int getSize(Activity aty, float dip) {
        DisplayMetrics dm = new DisplayMetrics();
        aty.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return new Float(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, dm)).intValue();
    }
}

